<template>
  <div class="search-result-container">
    <!-- 顶部导航 -->
    <div class="search-header">
      <button class="back-btn" @click="goBack">
        <SvgIcon iconName="icon-zuojiantou" fontSize="65px" color="red"></SvgIcon>
      </button>
      <div class="search-info">
        <h2>搜索结果</h2>
        <p>关键词："{{ searchKeyword }}"</p>
      </div>
    </div>

    <!-- 搜索结果统计 -->
    <div class="result-stats">
      <span>找到 {{ searchResults.length }} 个相关作品</span>
    </div>

    <!-- 搜索结果列表 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <div class="discover-items">
        <div class="discover-item" v-for="item in searchResults" :key="item.id" @click="goToNoteDetail(item)">
          <div class="discover-image">
            <img v-if="item.media_type === 'image'" :src="item.cover" :alt="item.title">
            <VideoPoster
              v-else-if="item.media_type === 'video'"
              :videoSrc="item.cover"
              width="100%"
              height="100%"
              :canvasWidth="320"
              :canvasHeight="180"
              @click="goToNoteDetail(item)"
            />
          </div>
          <div class="discover-title">{{ item.title }}</div>
          <div class="discover-user">
            <div class="user-info">
              <img :src="item.avatar" class="small-avatar" alt="用户头像">
              <span>{{ item.username }}</span>
            </div>
            <div class="publish-date">
              <svg class="calendar-icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19,4H18V2H16V4H8V2H6V4H5C3.9,4 3,4.9 3,6V20C3,21.1 3.9,22 5,22H19C20.1,22 21,21.1 21,20V6C21,4.9 20.1,4 19,4M19,20H5V10H19V20M19,8H5V6H19V8Z"/>
              </svg>
              <span class="date">{{ formatDate(item.time) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">
        <SvgIcon iconName="icon-sousuo1" fontSize="120px" color="#ccc"></SvgIcon>
      </div>
      <h3>没有找到相关内容</h3>
      <p>试试其他关键词吧</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import SvgIcon from '@/components/svgIcon.vue';
import VideoPoster from '@/components/VideoPoster.vue';

export default {
  name: 'SearchResult',
  components: {
    SvgIcon,
    VideoPoster
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const searchKeyword = ref('');
    const searchResults = ref([]);

    // 格式化日期
    const formatDate = (timestamp) => {
      if (!timestamp) return '未知日期';
      
      try {
        const date = new Date(timestamp);
        if (isNaN(date.getTime())) {
          return '未知日期';
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '未知日期';
      }
    };

    // 返回上一页
    const goBack = () => {
      router.go(-1);
    };

    // 跳转到笔记详情
    const goToNoteDetail = (item) => {
      router.push({
        path: '/mecont',
        query: {
          userId: item.user_id,
          noteId: item.id
        }
      });
    };

    // 搜索作品
    const searchNotes = async (keyword) => {
      try {
        // 获取所有笔记
        const notesResponse = await axios.get('http://1.14.98.17:8765/api/notes');
        if (!notesResponse.data.success) {
          console.error('获取笔记失败');
          return;
        }

        // 获取所有用户信息
        const usersResponse = await axios.get('http://1.14.98.17:8765/api/users');
        if (!usersResponse.data.success) {
          console.error('获取用户信息失败');
          return;
        }

        // 创建用户映射
        const userMap = new Map();
        usersResponse.data.data.forEach(user => {
          userMap.set(user.user_id, user);
        });

        // 过滤匹配的笔记
        const matchedNotes = notesResponse.data.data.filter(note => 
          note.title && note.title.toLowerCase().includes(keyword.toLowerCase())
        );

        // 获取每个笔记的详细信息
        const results = await Promise.all(
          matchedNotes.map(async (note) => {
            try {
              // 获取笔记媒体信息
              const mediaResponse = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/media`);
              let cover = '';
              let mediaType = 'image';
              
              if (mediaResponse.data.success && mediaResponse.data.data.length > 0) {
                const firstMedia = mediaResponse.data.data[0];
                cover = firstMedia.media_url;
                mediaType = firstMedia.media_type;
              }

              // 获取用户信息
              const user = userMap.get(note.user_id) || {};

              return {
                id: note.note_id,
                title: note.title || '无标题',
                cover: cover,
                media_type: mediaType,
                username: user.nickname || '匿名用户',
                avatar: user.avatar_url || '',
                user_id: note.user_id,
                time: note.updated_at || note.create_time || '',
                likes: note.like_count || 0
              };
            } catch (error) {
              console.error(`获取笔记 ${note.note_id} 详细信息失败:`, error);
              return null;
            }
          })
        );

        searchResults.value = results.filter(item => item !== null);
        console.log('搜索结果:', searchResults.value);
      } catch (error) {
        console.error('搜索失败:', error);
      }
    };

    onMounted(() => {
      const keyword = route.query.keyword;
      if (keyword) {
        searchKeyword.value = keyword;
        searchNotes(keyword);
      }
    });

    return {
      searchKeyword,
      searchResults,
      formatDate,
      goBack,
      goToNoteDetail
    };
  }
};
</script>

<style scoped>
.search-result-container {
  width: 750px;
  margin: 0 auto;
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 40px;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  background: none;
  border: none;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  font-size: 28px;
  transition: all 0.2s ease;
  border-radius: 50%;
  margin-right: 16px;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

.search-info {
  flex: 1;
}

.search-info h2 {
  margin: 0 0 4px 0;
  font-size: 32px;
  color: #333;
  font-weight: 600;
}

.search-info p {
  margin: 0;
  font-size: 24px;
  color: #666;
}

.result-stats {
  padding: 16px 24px;
  background-color: #f8f8f8;
  border-bottom: 1px solid #eee;
}

.result-stats span {
  font-size: 24px;
  color: #666;
}

.search-results {
  padding: 16px;
}

.discover-items {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  max-width: 760px;
  margin: 0 auto;
  justify-content: space-between;
}

.discover-item {
  width: calc(50% - 10px);
  height: 660px;
  margin: 10px 0;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.discover-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.discover-image {
  position: relative;
  height: 476px;
  overflow: hidden;
}

.discover-image img,
.discover-image video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.discover-title {
  width: 100%;
  height: 72px;
  margin: 15px 0 25px 3px;
  font-size: 28px;
  line-height: 1.3;
  font-weight: bold;
  color: #000;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.discover-user {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 15px;
}

.user-info {
  display: flex;
  align-items: center;
}

.small-avatar {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  margin-right: 8px;
}

.user-info span {
  font-size: 24px;
  color: #666;
  max-width: 130px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.publish-date {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background-color: rgba(0, 0, 0, 0.03);
  border-radius: 16px;
}

.calendar-icon {
  width: 20px;
  height: 20px;
  margin-right: 6px;
  color: #666;
}

.date {
  font-size: 20px;
  color: #666;
  font-weight: 500;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120px 24px;
  text-align: center;
}

.empty-icon {
  margin-bottom: 24px;
}

.empty-state h3 {
  font-size: 32px;
  color: #333;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.empty-state p {
  font-size: 24px;
  color: #666;
  margin: 0;
}
</style> 